package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;

import com.itheima.reggie.dto.SetmealDto;

import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @PostMapping
    @CacheEvict(value = "setmeal", allEntries = true)
    public R<String> save(@RequestBody SetmealDto dto) {
        setmealService.saveWithSetmealDish(dto);
        return R.success("新增套餐成功");
    }

    @GetMapping("/page")
    @Cacheable(value = "setmeal", key = "#page+'_'+#pageSize+'_'+#name", unless = "#result==null")
    public R<Page> page(int page, int pageSize, String name) {
        //创建分页查询
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //根据套餐名称模糊查询
        lqw.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        //排序
        lqw.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo, lqw);
        //返回的分页结果
        Page<SetmealDto> resultPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, resultPage, "records");
        //单独处理records
        List<Setmeal> records = pageInfo.getRecords();//从数据库中查询到集合
        List<SetmealDto> resultList = new ArrayList<>();
        for (Setmeal record : records) {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(record, setmealDto);
            Category category = categoryService.getById(record.getCategoryId());
            if (category != null) {
                setmealDto.setCategoryName(category.getName());
            }
            resultList.add(setmealDto);
        }
        resultPage.setRecords(resultList);
        return R.success(resultPage);
    }

    //删除套餐
    @DeleteMapping
    @CacheEvict(value = "setmeal", allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        setmealService.delete(ids);
        return R.success("删除套餐成功");
    }

    //修改套餐状态
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmeal", allEntries = true)
    public R<String> status(@PathVariable Integer status, @RequestParam List<Long> ids) {
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId, ids);
        setmealService.update(setmeal, lqw);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    @Cacheable(value = "setmeal", key = "#id")
    public R<SetmealDto> get(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    @PutMapping
    @CacheEvict(value = "setmeal", allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        setmealService.updateWithDish(setmealDto);
        return R.success("修改成功");
    }

    //根据套餐的id查询
    @GetMapping("list")
    @Cacheable(value = "setmeal", key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId()).
                eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        lqw.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(lqw);
        return R.success(list);
    }

    @GetMapping("/dish/{id}")
    @Cacheable(value = "setmeal",key = "#id",unless = "#result==null")
    public R<List<Dish>> getDish(@PathVariable Long id) {
        //根据套餐id查询里面的菜品信息
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishList = setmealDishService.list(lqw);
        //把套餐中的菜品循环查出来
        List<Dish> dishList=setmealDishList.stream().map((item) -> {
           //获取菜品集合中的id，根据菜品id查询菜品信息
            Long dishId = item.getDishId();
            Dish byId = dishService.getById(dishId);
            return byId;
        }).collect(Collectors.toList());
        return R.success(dishList);
    }
}
